// pages/scanForPay/index.js
const common = require("../../public.js");
Page({
    /**
     * 页面的初始数据
     */
    data: {
        cardDiscountAmount:0,// 是否使用折扣  0不使用   1使用,

        useTextRemind:'去使用',
        cardDiscountMoney:"",
        mostgoldToal:'',
        mostMoney:'',
        listShowMostMoney:'',
        paymentValue: '',
        storeId: '',
        receiverUserId: '',
        payRate:'',
        fyproBenefitItemRate:'',
        cityCouponNo: '',
        discountMoney: 0,
        step: 0,
        loading: false,
        employeeUserId: "",
        userType: "",
        name: "",
        coupListD: [],
        saveHasSelectList:[],
        requestFlag: true,
        discountsMoney: 0,
        show: true,
        orderId: '',
        userInfo: {},
        arrText: [

            {
                isSelect: false,
                name: '暂不使用金豆'
            },
            {
                isSelect: false,
                name: '抵扣￥1.00最高可使用100金豆'
            },
            {
                isSelect: false,
                name: '自定义使用金豆数量'
            },
        ],
        othercounts: 0,//
        glodPrice: 0,
        storeName: ''

    },
    // 金豆提交
    submit_clicks() {
        // if(this.data.goldValue<100){
        //       common.showToast('最低使用100个金豆')
        //     return;
        // }
        this.setData({
            showGold: false,
        })

    },
    onBlur(e) {
        var that = this;
        var num;
        if (e.detail.value == '' || !e.detail.value || e.detail.value == 0) {
            var counts = 0
        } else {
            counts = parseInt(e.detail.value)
console.log('fff---',counts);
            if (counts < 100) {
                common.showToast('最低使用100个金豆')
                counts = 0
                this.setData({
                    goldValue: '',
                    glodPrice: 0
                })
                return
            }
        }

    },
    // clearFunc(){
    //     counts = 0
    //     this.setData({
    //         goldValue: '',
    //         glodPrice: 0
    //     })
    // },
    //购买数量  计算数量金额加
    goldNumChange(e) {
        var that = this;
        var num;
        if (e.detail == '' || !e.detail || e.detail == 0) {
            var counts = 0
        } else {
          
            counts = parseInt(e.detail)
            console.log('nnnn--',counts);
            // console.log(this.data.paymentValue,"this.data.paymentValue")
            // console.log(counts,"countscountscountscounts")

    
    
            var mostCanUse = this.data.fyproBenefitItemRate*this.data.paymentValue*100;

            console.log('拥有--',this.data.goldValue,'===最高可用',mostCanUse);
            if(this.data.goldToal > mostCanUse){// 拥有>最高可用
                if(counts<100){// 输入小于100, 提示金豆数量最低使用100
                    // common.showToast('金豆数量最低使用100')
                    // counts = 0
                    // this.setData({
                    //     goldValue: '',
                    //     glodPrice: 0
                    // })
                }else if(counts>=100 && counts<= mostCanUse){// 大于等于100,小于等于最高可用  正常
                    this.setData({
                        goldValue: counts
    
                    })
                }else{
                    common.showToast('您输入的数量超限')
                    counts = 0
                    this.setData({
                        goldValue: '',
                        glodPrice: 0
                    })
                 }
            }else{// 拥有<最高可用
                if(counts<100){// 输入小于100, 提示金豆数量最低使用100
                    // common.showToast('金豆数量最低使用100')
                    // counts = 0
                    // this.setData({
                    //     goldValue: '',
                    //     glodPrice: 0
                    // })
                }else if(counts>=100 && counts<= this.data.goldToal){// 大于等于100,小于等于最高可用  正常
                    console.log('----counts---',counts);
                    this.setData({
                        goldValue: counts
    
                    })
                }else{
                    common.showToast('您输入的数量超限')
                    counts = 0
                    this.setData({
                        goldValue: '',
                        glodPrice: 0
                    })
                 }
            }




            // if ((parseFloat(this.data.paymentValue)) - (counts / 100) < 0) {
            //     common.showToast('不能超出付款金额')
            //     counts = 0
            //     this.setData({
            //         goldValue: '',
            //         glodPrice: 0
            //     })
            //     return
            // } else if (counts > this.data.goldToal) {
            //     common.showToast('超过拥有金豆数量')
            //     counts = 0
            //     this.setData({
            //         goldValue: '',
            //         glodPrice: 0
            //     })
            //     return
            // }

        }

        that.setData({
            counts, //金豆数量
            othercounts: counts
        }, () => {
            this.setData({
                glodPrice: parseInt(counts*100)/100,
                listShowMostMoney:parseInt(counts*100)/100/100,
            })
        })
    },
    // 金豆弹框
    goldFlag() {
        if (this.data.discountMoney) {
            common.showToast('优惠券和金豆不可同时使用')
            return
        }
          if (this.data.cardDiscountMoney) {
            common.showToast('会员折扣和金豆不可同时使用')
            return
        }


        //付款金额满100元才能使用金豆
        // if (this.data.paymentValue < 100) {
        //     common.showToast('付款金额满100可用')
        //     return
        // }
        console.log(parseFloat((this.data.paymentValue)))
        console.log(this.data.goldToal / 100)
        console.log(parseFloat((this.data.paymentValue)) - (this.data.counts / 100), "555555555")
        if (this.data.goldToal < 100) {
            common.showToast('暂不可用')
            return
        }
        if (parseFloat((this.data.paymentValue)) - (this.data.goldToal / 100) <= 0) {
            this.setData({
                goldToalXian: (this.data.paymentValue * 1000 * 100) / 1000,
                // counts:this.data.paymentValue*100
            })
        } else {
            this.setData({
                goldToalXian: this.data.goldToal,
                // counts:this.data.goldToal
            })
        }
        if (this.data.paymentValue == '') {
            common.showToast('请输入金额')
            return
        }
        if (this.data.paymentValue <1) {
            common.showToast('付款金额大于1元可使用金豆')
            return
        }
        this.setData({
            showGold: true
        })
    },
    click_index(e) {
        var that = this
        let {
            index,
            item
        } = e.currentTarget.dataset
        // let paymentValue = parseInt(this.data.paymentValue)
        this.setData({
            goldBean: false,
            // paymentValue,
        }, () => {
            console.log(this.data.counts, "444447777777777777777")
            console.log(index, "indexinxe")
            var suitGold = '';
            if (index == 0) {
                this.setData({
                    counts: 0,
                    goldValue:'',
                    othercounts: 0
                })
            } else if (index == 1) {

                console.log('前者',parseFloat((that.data.paymentValue))*that.data.fyproBenefitItemRate*100,'--后者---',that.data.goldToal);

                // var suitGold = '';
                if(that.data.goldToal>parseFloat((that.data.paymentValue))*that.data.fyproBenefitItemRate*100){// 拥有>最高可用
                    console.log('ff');
                    suitGold = parseInt(parseFloat((that.data.paymentValue))*that.data.fyproBenefitItemRate*100);
                }else{// 拥有<最高可用
                    console.log('gg');
                    suitGold = that.data.goldToal;
                }
                console.log('suitGold---',suitGold);
                

                this.setData({
                    counts:suitGold,
                    goldValue:'',
                    // counts: this.data.goldToalXian
                })
            } else if (index == 2) {
                this.setData({
                    counts: 0,
                    othercounts: 0,
                })
            }


            this.setData({
                activeIndex: index,
                
            })

            for (var i = 0; i < this.data.arrText.length; i++) {
                if (this.data.activeIndex == i) {
                    this.data.arrText[i].isSelect = true
                } else {

                    this.data.arrText[i].isSelect = false
                }
            }
                console.log('3434===',this.data.counts);

            this.setData({
                // glodPrice: parseInt(this.data.counts*100)/100,
                glodPrice: this.data.counts,
                listShowMostMoney:suitGold/100,
                arrText: this.data.arrText
            })


            // }
        })


    },
    onClose() {
        var that = this
        // var storePrice = (parseFloat(that.data.goodsInfo.price) - that.data.counts / 100 * app.globalData.discount).toFixed(2) //总价格
        this.setData({
            showGold: false,

            // storePrice
        });
    },
    getUserAssets() { // 获取余额
        const that = this
        const tempJson = {
            userId: that.data.userInfo.id,
            token: that.data.token
        }
        common.post('/userDeposit/getUserAssetsGold', tempJson, function (res) {
            if (res.status === 200) {
               
                var totalMoney = res.data.totalMoney;
                // totalMoney = 800;
                that.setData({
                    userAssets: res.data,
                    goldToal: totalMoney,//  totalMoney
                    counts: totalMoney,
                    goldToalTwo: totalMoney,

                }, () => {

                })
            } else {
                common.showRequestErrMsg(res)

            }
        })
    },

    // 跳转会员卡
    go_card(e) {
        let item = e.currentTarget.dataset.item
        if (item.id == 16) {
            wx.navigateToMiniProgram({
                appId: 'wxaf35009675aa0b2a',
                path: '/pages/index/index?dchn=0j55kav', //跳转目标页面+携带参数 滴滴
                extraData: {
                    a: '123' //携带参数
                },
                envVersion: 'release',
                success(res) {
                    // 打开成功
                    // debugger
                }
            })
            return
        }
        if (item.redirectUrl) {
            if (item.id == 17) {
                wx.navigateTo({
                    url: '/pages/crowd/List/index'
                })
            } else {
                wx.navigateTo({
                    url: '/packageA/pages/Goods/details/index?id=' + item.redirectUrl
                })
            }

        } else {
            if (item.id == 17) {
                wx.navigateTo({
                    url: '/pages/crowd/List/index'
                })
            } else {
                wx.navigateTo({
                    url: item.redirectPath + '?managerId=' + item.managerId,
                })
            }
        }
    },
    // 跳转
    click_go() {
        wx.navigateTo({
            url: '/packageC/pages/drawList/drawList',
        })
    },
    // 首页第二轮播图
    adverList() {
        var that = this
        common.get('/advertisements/searchAdvertisementByModule', {}, res => {
            if (res.status === 200) {
                // let arr = res.data

                // let numRandom
                // arr.forEach((item, index) => {
                //     // 取随机数作为随机数组下标
                //      numRandom = parseInt(Math.random() * arr.length)
                // })
                // console.log(numRandom)
                that.setData({
                    // tiaoBan: res.data[numRandom].imgUrl
                    tiaoBan: res.data
                })
            } else {
                // common.showRequestErrMsg(res)
            }
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    click_show() {
        console.log("111111111111")
        this.setData({
            show: false
        })
    },
    goBack() {
        const pages = getCurrentPages();
        const prevPage = pages[pages.length - 2]; //上一个页面
        // 从朋友圈进入的时候，页面栈为空，这里需要判断是否有上个页面
        if (prevPage) {
            wx.navigateBack({
                delta: 1
            })

        } else {
            wx.navigateTo({
                url: '/pages/index/index',
            })
        }
    },
    onLoad: function (options) {
        console.log(options, "541")
        var that = this
        this.adverList()
        //获取胶囊位置
        let capsule = wx.getMenuButtonBoundingClientRect()
        this.setData({
            height: capsule.height,
            top: capsule.top,
        })
        var windowHeight = wx.getSystemInfoSync().windowHeight
        var windowWidth = wx.getSystemInfoSync().windowWidth
        this.setData({
            scroll_height: windowHeight * 750 / windowWidth - 200
        })


          


        console.log("进来eeee")
        if (options.q) {
            let scan_url = decodeURIComponent(options.q);
            console.log("进来0")
            // https://www.feiyang.life/#/pay/scanForPay?receiverUserId=29719&storeId=2151&userType=0&employeeUserId=
            let pos1 = scan_url.indexOf("receiverUserId="); // 
            let pos2 = scan_url.indexOf("&storeId="); // 
            let pos3 = scan_url.indexOf("&userType"); // 
            let pos4 = scan_url.indexOf("&employeeUserId"); // 
            

            var receiverUserId = scan_url.substring(pos1+15, pos2)
            var storeId = scan_url.substring(pos2+9, pos3)
            var userType = scan_url.substring(pos3+10, pos4)
            var employeeUserId = scan_url.substring(pos4+16, scan_url.length)
          
            options.receiverUserId = receiverUserId;
            options.storeId = storeId;
            options.userType = userType;
            options.employeeUserId = employeeUserId;
            console.log('赋值后--receiverUserId--',options.receiverUserId,'---storeId',options.storeId,'---userType',options.userType,'---employeeUserId',options.employeeUserId);
            console.log('位置pos1----',pos1,'====pos2==',pos2,'---pos3--',pos3,'--pos4--',pos4,'--总长度---',scan_url.length);

            

            if (options.userType != "undefined") {
                this.setData({
                    userType: options.userType
                })
            } else {
                this.setData({
                    userType: ""
                })
            }
            if (options.employeeUserId != "undefined") {
                this.setData({
                    employeeUserId: options.employeeUserId
                })
            } else {
                this.setData({
                    employeeUserId: ""
                })
            }
            this.data.storeId = options.storeId
            this.data.receiverUserId = options.receiverUserId
            common.getLocalUserInfo((success, data) => {
                if (success) {
                    console.log('嘻哈---',options.storeId);
                    console.log(data)
                    this.data.userInfo = data.user
                    this.data.token = data.token
                    this.data.openid = data.openid
                    console.log('huhu---',this.data.employeeUserId);
                    this.getStoreInfo(options.storeId)
                    // this.getUserAssets()
                    // this.getStoreName(options.storeId)
                }
            }, true)
            return
            //  公眾號
        }
        console.log(options, "77777788888")

        if (options.name) {
            this.setData({
                name: options.name ? options.name : ''
            })
        }
        if (options.userType != "undefined") {
            this.setData({
                userType: options.userType
            })
        } else {
            this.setData({
                userType: ""
            })
        }
        if (options.employeeUserId) {
            if (options.employeeUserId != "undefined" && options.employeeUserId != "null") {
                this.setData({
                    employeeUserId: options.employeeUserId
                })
                console.log("44444")
            } else {
                this.setData({
                    employeeUserId: ""
                })
                console.log("666666")
            }
        } else {
            console.log("44125555")
            this.setData({
                employeeUserId: ""
            })
        }

        this.data.storeId = options.storeId
        this.data.receiverUserId = options.receiverUserId
        if (options.token) {
            this.data.token = options.token
            this.data.openid = options.xcxOpenid
            this.data.userInfo.id = options.userId
            // this.getStoreInfo(options.storeId)
            this.getStoreInfo(options.storeId)
            return
        }
        common.getLocalUserInfo((success, data) => {
            if (success) {
                this.data.userInfo = data.user
                this.data.token = data.token
                this.data.openid = data.openid
                this.getStoreInfo(options.storeId)
                // this.getUserAssets()
                // this.getStoreName(options.storeId)
            }
        }, true)
    },
    // 店铺名称
    getStoreName(storeId) {
        this.setData({
            loading: true
        })
        const param = {
            storeId,
            employeeId: this.data.employeeUserId,
            userId: this.data.userInfo.id,
        }
        common.post('/store/getStoreAndBranchInfo',
            param,
            res => {
                if (res.status === 200) {
                    this.setData({
                        storeName: res.data.name
                    })
                }
            },
            () => {
                this.setData({
                    loading: false
                })
            })
    },
    getStoreInfo(storeId) {
        var that = this;
        this.setData({
            loading: true
        })
        console.log('xxxx-');
        const param = {
            storeId,
            // employeeId: this.data.employeeUserId,
            employeeId: "",
            userId: this.data.userInfo.id,
        }
        console.log('jjj',param);
        common.post('/store/getStoreAndBranchInfo',
            param,
            res => {
                console.log('信息为--',res);
                if (res.status === 200) {
                    this.setData({
                        // storeInfo: res.data.store,
                        fyproBenefitItemRate: res.data.fyproBenefitItemRate,
                        payRate:res.data.payRate==1?0:res.data.payRate,
                        storeName: res.data.name,
                        storeImage:  res.data.storeImage,
                    }, function () {
                        that.getUserAssets()
                      })
                     
                


                }
            },
            () => {
                console.log('dsadsdsd');
                this.setData({
                    loading: false
                })
            })
    },
    // 跳转惠民券
    jumpCompanyList() {
        if (this.data.paymentValue <= 0) {
            common.showToast('请输入金额')
        } else {
            wx.navigateTo({
                url: '/packageA/pages/scanForPay/CompanyList/index?storeId=' +
                    this.data.storeId + '&userId=' +
                    this.data.userInfo.id + '&token=' +
                    this.data.token + '&paymentValue=' +
                    this.data.paymentValue
            })
        }
    },
    cantUseCardDiscountClick(){
        this.setData({
            cardDiscountMoney:''
        })
    },

   
    useCardDiscountClick(e){
        console.log('这里---',e.currentTarget.dataset.index)
        console.log('cardDiscountMoney---',this.data.cardDiscountMoney)
        var that = this;
     if(!this.data.paymentValue){
         return   common.showToast('请输入金额');
     }
  
     if ( this.data.activeIndex==1||this.data.goldValue) {
        common.showToast('金豆和会员折扣不可同时使用')
        return
    }

    if (this.data.discountMoney) {
        common.showToast('优惠券和会员折扣不可同时使用')
        return
    }

        this.setData({
       
            cardDiscountMoney:e.currentTarget.dataset.index==0?parseInt(this.data.paymentValue*100)/100*parseInt(100-this.data.payRate*100)/100:'',
            useTextRemind:e.currentTarget.dataset.index==0?'取消使用':'去使用',
            cardDiscountAmount:e.currentTarget.dataset.index==0?1:0,
          
        
        })
    },
    
    jumpUnionVoucher() {
        // console.log('hasSelectPNo', this.data.hasSelectPNo)
        if (this.data.paymentValue <= 0) {
            common.showToast('请输入金额')
        } else {
            console.log('一月又一月====',this.data.goldValue);
           
            if ( this.data.activeIndex==1||this.data.goldValue) {
                common.showToast('金豆和优惠券不可同时使用')
                return
            }
            if (this.data.cardDiscountMoney) {
                common.showToast('会员折扣和优惠券不可同时使用')
                return
            }
            console.log('扫码页--',this.data.saveHasSelectList);
            var saveHasSelectList = this.data.saveHasSelectList.length?JSON.stringify(this.data.saveHasSelectList):''
            wx.navigateTo({
                url: '/pages/scanForPay/unionVoucher/index?storeId=' +
                    this.data.storeId + '&userId=' +
                    this.data.userInfo.id + '&token=' +
                    this.data.token + '&paymentValue=' +
                    this.data.paymentValue + '&saveHasSelectList=' +
                    saveHasSelectList
            })
        }
    },
    jumpVoucherList() {
        // console.log('hasSelectPNo', this.data.hasSelectPNo)
        if (this.data.paymentValue <= 0) {
            common.showToast('请输入金额')
        } else {
            wx.navigateTo({
                url: '/pages/scanForPay/voucherList/index?storeId=' +
                    this.data.storeId + '&userId=' +
                    this.data.userInfo.id + '&token=' +
                    this.data.token + '&paymentValue=' +
                    this.data.paymentValue
            })
        }
    },
    inputValue(e) {
        console.log("bianhua")
        var that = this;
        let value = e.detail.value
        if (value.indexOf('.') == 0) { //第一位就是 .
            value = '0' + value
        }
        value = value.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符
        value = value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
        value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
        value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
        // 当金额发生改变，取消优惠券使用
        let arrText = [

            {
                isSelect: false,
                name: '暂不使用金豆'
            },
            {
                isSelect: false,
                name: '抵扣￥1.00最高可使用100金豆'
            },
            {
                isSelect: false,
                name: '自定义使用金豆数量'
            },
        ]
console.log('本次输入的值',value,'输入后',that.data.goldToal,'===fff==',that.data.fyproBenefitItemRate*value*100);
        this.setData({
            paymentValue: value,
            discountMoney: 0,
            cityCouponNo: '',
            coupListD: [],
            saveHasSelectList:[],
            discountsMoney: 0,
            activeIndex: -1,
            //  64.85*0.5*100
            mostgoldToal:that.data.goldToal>that.data.fyproBenefitItemRate*value*100?parseInt(that.data.fyproBenefitItemRate*parseInt(value*100)*100/100):that.data.goldToal,
            glodPrice: 0,
            arrText
        },()=>{
            this.setData({
                mostMoney:this.data.mostgoldToal/100,
                listShowMostMoney:this.data.mostgoldToal/100,
            })
        })
        return value
    },
    jia() {
        // console.log(,"cehsishjjj")

        this.setData({
            requestFlag: true,
        })
    },
    commit: common.throttleFunc(function () {
        if (this.data.paymentValue <= 0) {
            common.showToast('请输入金额')
            return
        }

        console.log('---saveHasSelectList---',this.data.saveHasSelectList);
        const param = {
            storeId: this.data.storeId,
            receiverUserId: this.data.receiverUserId,

            userId: this.data.userInfo.id,
            xcxOpenid: this.data.openid,
            totalAmount: this.data.paymentValue,
            discountMoney: 0,
            adminCouponNo: this.data.coupListD[0] || "",
            employeeUserId: this.data.employeeUserId,
            // employeeUserId:"",
            compositCoupon: this.data.cityCouponNo,
            goldPrice:  parseInt(this.data.glodPrice*100)/100,//金豆的数量
            token: this.data.token,
            // discountMoney: this.data.discountMoney,
            userType: this.data.userType,
            cardDiscountAmount:this.data.cardDiscountAmount,// 是否使用折扣  0不使用   1使用,
            // userDiscountCouponId: this.data.userDiscountCouponId || '' //企业券
            userDiscountCouponId: this.data.saveHasSelectList.length?this.data.saveHasSelectList[0]:'' //企业券
        }

        this.setData({
            loading: true
        })
        const that = this
        console.log('扫码付款参数',param);
        // return;
        common.wxPayRequest('/chinaumsPayForScanPaymentFYPlatform', param, function (res) {
            // console.log(res.data.merOrderId,"测试")
            if (res.status === 200) {


                if (typeof res.data != 'object') {
                    if (res.data.indexOf('freePay') != -1) {
                        let orderId = res.data.substring(7)
                        console.log(orderId,"555566666")
                        that.setData({
                            orderId
                        })
                        that.showSuccess()
                        return
                    }
                } else {
                    that.setData({
                        orderId: res.data.merOrderId
                    })
                }



                //微信支付
                wx.requestPayment({
                    'timeStamp': res.data.timeStamp,
                    'nonceStr': res.data.nonce_str,
                    'package': res.data.package,
                    'signType': res.data.signType,
                    'paySign': res.data.paySign,
                    // "success": function (res) {
                    //   console.log("拉起来了")
                    //   console.log(res)
                    // },
                    // "fail": function (res) {
                    //   console.log(res)
                    // },
                    // "complete": function (res) {
                    //   console.log(res)
                    // }
                    'success': function (res) {
                        console.log(res, '测试车次号')
                        if (res.errMsg == "requestPayment:ok") {
                            console.log('成功');
                        }
                        console.log(res)
                        that.showSuccess()
                    },

                    'fail': function (res) {
                        console.log(res, '失败')
                        if (res.errMsg === 'requestPayment:fail cancel') { } else {

                            common.showToast(res.errMsg)
                        }
                    }
                })
            } else {
                common.showRequestErrMsg(res)
            }
        }, function () {
            that.setData({
                requestFlag: false,
                loading: false
            })
        })
    }, 3000),

    showSuccess() {
        this.setData({
            step: 1
        })
    },

    onUnload: function () {
        // console.log("1111")
        // if (this.data.name = 'lanling') {
        //     wx.navigateTo({
        //         url: '/pages/Dj/index',
        //     })
        // }
        // wx.navigateTo({
        //     url: '/pages/index/index',
        // })
    },
})